package com.lean.android.ad.core.reward

import android.app.Activity
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.widget.FrameLayout
import androidx.annotation.RestrictTo
import com.bytedance.sdk.openadsdk.TTRewardVideoAd.RewardAdInteractionListener
import com.lean.android.ad.core.AdLoaders
import com.lean.android.ad.core.AdRenderer
import com.lean.android.ad.core.AdSdk
import com.lean.android.ad.core.ErrorCode
import com.lean.android.ad.core.R
import com.lean.android.ad.core.RewardAdRenderCallback
import com.lean.android.ad.repository.ReportHelper
import com.lean.android.ad.repository.ReportHelper.toCpmInt
import com.lean.android.ad.utils.AdLog

@RestrictTo(RestrictTo.Scope.LIBRARY)
class RewardAdRenderer(private val activity: Activity) :
    AdRenderer<RewardAd, RewardAdRenderCallback> {

    private fun attachCustomFloatView() {
        val topActivity = AdSdk.getTopActivity() ?: return
        val customFloatView = AdSdk.getAdConfig().rewardCustomFloatView ?: return
        val contentView = customFloatView.onCreateView(LayoutInflater.from(activity))
        customFloatView.onViewCreated(contentView)
        contentView.id = R.id.id_reward_custom_float_view

        val contentParent =
            topActivity.window.decorView.findViewById<FrameLayout>(android.R.id.content)
        contentParent.addView(contentView)
    }

    private fun removeCustomFloatView() {
        val topActivity = AdSdk.getTopActivity() ?: return
        val contentParent =
            topActivity.window.decorView.findViewById<FrameLayout>(android.R.id.content)
        val floatView = contentParent.findViewById<View>(R.id.id_reward_custom_float_view) ?: return
        contentParent.removeView(floatView)
    }

    override fun render(ad: RewardAd, renderCallback: RewardAdRenderCallback) {
        val nativeAd = ad.nativeAd
        var rewardVerified = false
        if (nativeAd.mediationManager.isReady) {
            nativeAd.setRewardAdInteractionListener(object : RewardAdInteractionListener {
                override fun onAdShow() {
                    AdLog.d(AdLog.AdRewardLoadTag, "RewardAd onAdShow")
                    nativeAd.mediationManager?.showEcpm?.also { cpmInfo ->
                        val cpm = cpmInfo.ecpm.toCpmInt()
                        ReportHelper.reportAdEvent(
                            requestId = ad.requestId,
                            eventType = ReportHelper.AdEventType.AdShowed,
                            platformId = cpmInfo.sdkName.orEmpty(),
                            adPosition = ReportHelper.AdPositionType.RewardVideo,
                            cpm = cpm
                        )
                    }

                    attachCustomFloatView()
                    renderCallback.onAdShow(ad, 0, 0)
                }

                override fun onAdVideoBarClick() {

                }

                override fun onAdClose() {
                    AdLog.d(
                        AdLog.AdRewardLoadTag,
                        "RewardAd onAdClose ， rewardVerified $rewardVerified"
                    )
                    removeCustomFloatView()
                    if (rewardVerified) {
                        renderCallback.onReward()
                    } else {
                        renderCallback.onInvalid(ErrorCode.ErrorRewardAdInvalid)
                    }
                }

                override fun onVideoComplete() {
                    AdLog.d(AdLog.AdRewardLoadTag, "RewardAd onVideoComplete")
                }

                override fun onVideoError() {
                    AdLog.d(AdLog.AdRewardLoadTag, "RewardAd onVideoError")
                    AdLoaders.toast(activity, "广告加载失败，请重试~")
                    renderCallback.onInvalid(ErrorCode.ErrorRewardAdVideoError)
                }

                override fun onRewardVerify(
                    p0: Boolean, p1: Int, p2: String?, p3: Int, p4: String?
                ) {

                }

                override fun onRewardArrived(isRewardValid: Boolean, rewardType: Int, p2: Bundle?) {
                    AdLog.d(AdLog.AdRewardLoadTag, "RewardAd onRewardArrived $isRewardValid")
                    rewardVerified = true
                }

                override fun onSkippedVideo() {
                    AdLog.d(AdLog.AdRewardLoadTag, "RewardAd onSkippedVideo")
                }
            })
            nativeAd.showRewardVideoAd(activity)
        } else {
            AdLoaders.toast(activity, "广告加载失败，请重试~")
            AdLog.d(AdLog.AdRewardLoadTag, "RewardAd is not ready to show, skip.")
            renderCallback.onInvalid(ErrorCode.ErrorRewardAdNotReady)
        }
    }
}